package com.wufun.overseas.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.papa.controller.core.ControllerManager;
import com.wufun.overseas.R;
import com.wufun.overseas.dialog.HandShankDialog;
import com.wufun.overseas.joystick.map.BlackListManager;
import com.wufun.overseas.main.base.MyApplication;
import com.wufun.overseas.models.bean.CommonRequestBean;
import com.wufun.overseas.models.bean.HandShankAdBean;
import com.wufun.overseas.models.bean.IntentDateBean;
import com.wufun.overseas.models.bean.ResultMainBean;
import com.wufun.overseas.models.db.HandShankTable;
import com.wufun.overseas.models.greendao.gen.HandShankTableDao;
import com.wufun.overseas.rpc.RpcClient;
import com.wufun.overseas.tools.BackgroundExecutor;
import com.wufun.overseas.utils.IntentUtil;
import com.wufun.overseas.utils.NetWorkUtils;
import com.wufun.overseas.utils.RequestBeanUtil;
import com.wufun.overseas.utils.ToastUtils;
import com.wufun.overseas.view.HandShankAdView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by caowd on 2015/6/9.
 * 有手柄的页面
 */

public class HandShankYesActivity extends HandShankBaseActivity {

    @Bind(R.id.listview)
    ListView    listview;
    @Bind(R.id.handshank_tip_lay)
    FrameLayout handshank_tip_lay;
    @Bind(R.id.rightButn)
    Button      rightButn;
    @Bind(R.id.papahandList)
    TextView    papahandList;

    private MyAdapter adapter;
    HandShankTableDao dao;

    private ArrayList<ControllerManager.ControllerDevice> mGameControllers;
//    GameControllerManager mGameControllerManager;

    public ArrayList<HandShankTable> onLineHandShankTableInfos = new ArrayList<HandShankTable>();//记录已连接手柄
    private List<HandShankTable>       dataBaseInfos;//数据库中历史记录
    private LinkedList<HandShankTable> data;//界面显示列表

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handshank_layout_yes);
        ButterKnife.bind(this);
//        rpcClient = new RpcClient();
        dao = MyApplication.getMyApplication().getSession().getHandShankTableDao();
        afterView();
    }

    @OnClick(R.id.rightButn)
    void rightButn() {
        startActivity(new Intent(Settings.ACTION_BLUETOOTH_SETTINGS));
    }

//    @Bind(R.id.mAdView)
//    HandShankAdView mAdView;
//    RpcClient rpcClient;

    void getAdData() {
        BackgroundExecutor.execute(new BackgroundExecutor.Task("", 0L, "") {

                                       @Override
                                       public void execute() {
                                           try {
                                               getAdData1();
                                           } catch (final Throwable e) {
                                               Thread.getDefaultUncaughtExceptionHandler().uncaughtException(Thread.currentThread(), e);
                                           }
                                       }
                                   }
        );
    }

    void getAdData1() {
//        try {
//            CommonRequestBean               requestBean = DotRequestTable.getInstance(this).getHandShankAdList();
//            ResultMainBean<HandShankAdBean> response    = rpcClient.getHandShankAdList(requestBean);
//            if (response.getCode() == 600) {
//                mAdView.updateViewByData(response.getMessages().getData());
//            } else {
//                mAdView.showDefaultView();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            mAdView.showDefaultView();
//        }
    }
//    void getAdData1() {
//        try {
//            CommonRequestBean               requestBean = DotRequestTable.getInstance(this).getHandShankAdList();
//            ResultMainBean<HandShankAdBean> response    = rpcClient.getHandShankAdList(requestBean);
//            if (response.getCode() == 600) {
//                mAdView.updateViewByData(response.getMessages().getData());
//            } else {
//                mAdView.showDefaultView();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            mAdView.showDefaultView();
//        }
//    }

    @OnClick(R.id.papahandList)
    void papahandList() {
        IntentDateBean intentDateBean = new IntentDateBean();
        intentDateBean.setLink_type(4);
        intentDateBean.setLink_type_val("http://h5.papa91.com/wf_shoubing.html");
        IntentUtil.getInstance().goShareWebActivity(this, intentDateBean);
    }

    public void loadAdData() {
        if (NetWorkUtils.isNetworkConnected(this)) {
            getAdData();
        } else {
//            mAdView.showNoNetWork();
        }
    }

    //    @AfterViews
    void afterView() {
        loadAdData();
        //打点
//        StatFactory.getInstance(this).sendDJoystickSetting(AccountUtil_.getInstance_(this).getUid(), AccountUtil_.getInstance_(this).isTourist(), "", "", 0);

        initView();
    }

    @Override
    protected void onResume() {
        setSpp4CheckInfo(true);
        super.onResume();
    }

    private void initView() {
        rightButn.setVisibility(View.VISIBLE);
        View view = LayoutInflater.from(HandShankYesActivity.this).inflate(R.layout.handshank_list_foot, null);
        dataBaseInfos = new ArrayList<HandShankTable>();
        data = new LinkedList<HandShankTable>();
        dataBaseInfos.addAll(findForTime());
        data.addAll(dataBaseInfos);

        adapter = new MyAdapter();
        listview.addFooterView(view);
        listview.setAdapter(adapter);

        view.findViewById(R.id.lay_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (haveConnectedDevices()) {
                    Intent intent = new Intent(v.getContext(), HandShankMapKeyActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.getInstance(HandShankYesActivity.this).showToastSystem(getString(R.string.gamepad_conn_required));
                }
            }
        });
        if (isBlueEnabled()) {
            handshank_tip_lay.setVisibility(View.GONE);
        } else {
            if (haveConnectedDevices()) {
                handshank_tip_lay.setVisibility(View.GONE);
            } else {
                handshank_tip_lay.setVisibility(View.VISIBLE);
            }
        }
    }

    private boolean haveConnectedDevices() {
        boolean isConnected = false;
        if (null != data && data.size() > 0) {
            synchronized (data) {
                for (HandShankTable table : data) {
                    if (table.getIsConnect()) {
                        isConnected = true;
                        break;
                    }
                }
            }
        }
        return isConnected;
    }

    //region GameControllerManager initView

    @Override
    public void onControllerDeviceChanged(int state, List<ControllerManager.ControllerDevice> controllerDevices) {
        handleChanged(controllerDevices);
    }

    private void handleChanged(List<ControllerManager.ControllerDevice> list) {
        try {
            if (mGameControllers == null)
                mGameControllers = new ArrayList<ControllerManager.ControllerDevice>();

            List<ControllerManager.ControllerDevice> connectDevices = new ArrayList<ControllerManager.ControllerDevice>();
            if (list != null)
                connectDevices.addAll(getValidDevice(list));

            onLineHandShankTableInfos.clear();
            HandShankTable handShankTable;
            ControllerManager.ControllerDevice device;
            if (connectDevices.size() != 0) {
                for (int i = 0; i < connectDevices.size(); i++) {
                    device = connectDevices.get(i);
                    handShankTable = new HandShankTable();
                    handShankTable.setName(device.getName());
                    handShankTable.setAddress(device.getAddress());
                    handShankTable.setTime(System.currentTimeMillis());
                    handShankTable.setIsConnect(true);

                    if (onLineHandShankTableInfos.contains(handShankTable)) {
                        continue;
                    } else {
                        onLineHandShankTableInfos.add(handShankTable);
                        data.remove(handShankTable);
                        data.addFirst(handShankTable);

                        refreshConnectState(true);
                    }
                }

                handshank_tip_lay.setVisibility(View.GONE);
                adapter.notifyDataSetChanged();
            } else
                refreshConnectState(false);

            //save instance
            mGameControllers.clear();
            if (list != null)
                mGameControllers.addAll(connectDevices);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //endregion
    //endregion


    @OnClick(R.id.backImage)
    void backImage() {
        finish();
    }

    private void parseConnectBlue() {
        handshank_tip_lay.setVisibility(View.GONE);

        HandShankTable newHandShankTable = null;
        for (HandShankTable handShankTable : onLineHandShankTableInfos) {
            if (!dataBaseInfos.contains(handShankTable)) {
                newHandShankTable = handShankTable;

                sendJoystickInfo(handShankTable);
            }
        }
        if (newHandShankTable != null) {
            showDialog(newHandShankTable.getName());
        }


        dataBaseInfos = findForTime();

        //清空数据
        data.clear();
        //加入在线
        data.addAll(onLineHandShankTableInfos);
        //加入离线
        dataBaseInfos.removeAll(onLineHandShankTableInfos);
        for (HandShankTable table :
                dataBaseInfos) {
            table.setIsConnect(false);
        }
        data.addAll(dataBaseInfos);

        //更新
        adapter.notifyDataSetChanged();
        dataBaseInfos.clear();
        dataBaseInfos.addAll(data);
        saveDataBase(data);
    }

    //    @Background
    void sendJoystickInfo(HandShankTable handShankTable) {
//        if (!isExist(handShankTable.getAddress())) {
//            JoyStickConfig joystickConfig = new JoyStickConfig();
//
//            AccountBean accountBean = AccountUtil_.getInstance_(this).getAccountData();
//            if (accountBean == null)
//                joystickConfig.setUid(0);
//            else
//                joystickConfig.setUid(accountBean.getUid());
//
//            joystickConfig.setGamepad_name(handShankTable.getName());
//            joystickConfig.setGamepad_mac(handShankTable.getAddress().replace(":", "_"));
//            joystickConfig.setUpdate_time(handShankTable.getTime());
//            StatFactory.getInstance(this).sendJoyStickInfoPost(JsonMapper.nonDefaultMapper().toJson(joystickConfig), AccountUtil_.getInstance_(this).getUid());
//        }
    }

    private void notifyNoDeviceConnect() {
        if (handshank_tip_lay != null) {
            handshank_tip_lay.setVisibility(View.VISIBLE);
            //Toast.makeText(this,R.string.no_bluetooth_connected_tip,Toast.LENGTH_SHORT).show();
        }
        dataBaseInfos = findForTime();
        data.clear();
        data.addAll(dataBaseInfos);
        for (HandShankTable table :
                data) {
            table.setIsConnect(false);
        }

        adapter.notifyDataSetChanged();
        saveDataBase(data);
    }

    private void showDialog(String name) {
        final HandShankDialog handShankDialog = new HandShankDialog(HandShankYesActivity.this);
        handShankDialog.setTitle(name);
        handShankDialog.setCancelClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                handShankDialog.dismiss();
            }
        });

        handShankDialog.setCheckClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(HandShankYesActivity.this, HandShankCheckKeyActivity.class));
                handShankDialog.dismiss();
            }
        });
        handShankDialog.show();
    }

    protected synchronized void refreshConnectState(Boolean isConnect) {
        if (isConnect) {
            parseConnectBlue();
        } else {
            notifyNoDeviceConnect();
        }
    }

    //    @Background
    void saveDataBase(List<HandShankTable> dataBaseInfos) {
        try {
            synchronized (dao) {
                for (HandShankTable handShankTable : dataBaseInfos) {
                    if (!BlackListManager.getInstance().isInBlackList(handShankTable.getName())) {
                        createOrUpdate(handShankTable);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class MyAdapter extends BaseAdapter {

        private String TAG = getClass().getSimpleName();

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int i) {
            return data.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            try {
                if (view == null) {
                    view = LayoutInflater.from(HandShankYesActivity.this).inflate(R.layout.handshank_item, null);
                }
                if (data.get(i).getIsConnect()) {
                    ((ImageView) view.findViewById(R.id.img)).setImageResource(R.drawable.handshank_on_icon);
                    ((ImageView) view.findViewById(R.id.handshank_blue_arrow_img)).setImageResource(R.drawable.handshank_blue_open_icon);
                    ((TextView) view.findViewById(R.id.dsc)).setTextColor(getResources().getColor(R.color.handshank_connected_txt));
                    ((TextView) view.findViewById(R.id.dsc)).setText(getString(R.string.gamepad_conn_tip_connected));
                } else {
                    ((ImageView) view.findViewById(R.id.img)).setImageResource(R.drawable.handshank_off_icon);
                    ((TextView) view.findViewById(R.id.dsc)).setTextColor(getResources().getColor(R.color.handshank_disconnected_txt));
                    ((TextView) view.findViewById(R.id.dsc)).setText(getString(R.string.gamepad_conn_tip_disconnected));
                    ((ImageView) view.findViewById(R.id.handshank_blue_arrow_img)).setImageResource(R.drawable.handshank_blue_close_icon);
                }

                ((TextView) view.findViewById(R.id.handshank_name)).setText(data.get(i).getName());


                String address = data.get(i).getAddress();
//                Logger.log(TAG, "device address=" + address);
                if (isBluetoothDeviceByMac(address)) {
                    view.findViewById(R.id.handshank_blue_arrow_img).setVisibility(View.VISIBLE);
                } else {
                    view.findViewById(R.id.handshank_blue_arrow_img).setVisibility(View.INVISIBLE);

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return view;
        }

        private boolean isBluetoothDeviceByMac(String mac) {
//            String mac="00:E0:20:1C:7C:0C";
            boolean ret = false;

            //正则校验MAC合法性
            String patternMac = "^[A-F0-9]{2}(:[A-F0-9]{2}){5}$";
            if (Pattern.compile(patternMac).matcher(mac.toUpperCase()).find()) {
                ret = true;
            } else {
//                addFieldError("macaddress", "MAC地址格式或者大小写错误");
            }

            return ret;
        }
    }


    //region DB handle
    public List<HandShankTable> findForTime() {
        List<HandShankTable> list = null;
        try {
            list = null;
            list = dao.queryBuilder().distinct().orderDesc(HandShankTableDao.Properties.Time).list();

            for (int i = 0; i < list.size(); i++) {
                HandShankTable handShankTable = list.get(i);
                if (BlackListManager.getInstance().isInBlackList(handShankTable.getName())) {
                    dao.delete(handShankTable);
                    list.remove(i);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public boolean isExist(String address) {
        try {
            List<HandShankTable> list = dao.queryBuilder().orderDesc(HandShankTableDao.Properties.Time).where(HandShankTableDao.Properties.Address.eq(address)).list();
            if (list != null && list.size() > 0)
                return true;
        } catch (Exception e) {
//            e.printStackTrace();
        }
        return false;
    }

    public void createOrUpdate(HandShankTable handShankTable) {
        if (isExist(handShankTable.getAddress())) {
            dao.update(handShankTable);
        } else
            dao.insertOrReplace(handShankTable);
    }
    //endregion
}
